package com.duguo.dynamicmvc.demo.itest;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;

public class AbstractJettyRunner {

	private static String _baseUrl;

	private Server _jetty;

	private int _port;

	private String _contextPath;

	private String _warPath;

	@BeforeSuite(groups = { "quickstart" })
	public void init() throws Exception {
		initParams();
		if (_port > 0)
			startJetty();
	}

	@AfterSuite(groups = { "quickstart" })
	public void destroy() {
		if (_port > 0) 
			stopJetty();
	}

	public static String getBaseUrl() {
		if (_baseUrl == null)
			initBaseUrl();
		return _baseUrl;
	}

	private static void initBaseUrl() {
		_baseUrl = System.getProperty("baseUrl","");
		if (!_baseUrl.startsWith("http")) {
			_baseUrl = "http://localhost:" + Integer.parseInt(System.getProperty("serverport", "17070")) + "/"
					+ System.getProperty("artifactId") + "/";
		}
	}

	private void initParams() {
		// if baseUrl setted in properties, we will test remote site
		if (!System.getProperty("baseUrl","").startsWith("http")) {
			_port = Integer.parseInt(System.getProperty("serverport", "17070"));
			_contextPath = System.getProperty("artifactId");
			_warPath = System.getProperty("version");
			assert (_contextPath != null);
			assert (_warPath != null);
			_warPath = "target/" + _contextPath + "-" + _warPath + "";
			_baseUrl = "http://localhost:" + _port + "/" + _contextPath + "/";
		}
	}

	private void startJetty() {
		try {

			_jetty = new Server(_port);

			WebAppContext context = new WebAppContext();
			// context.setContextPath(_contextPath);
			context.setContextPath("/" + _contextPath);
			context.setWar(_warPath);

			_jetty.addHandler(context);
			_jetty.start();
		} catch (Exception ex) {
			throw new RuntimeException("Failure starting Jetty instance: " + ex.toString(), ex);
		}
	}

	private void stopJetty() {
		try {
			if (_jetty != null) {
				Server tempJetty = _jetty;
				_jetty = null;
				tempJetty.stop();
			}
		} catch (Exception ex) {
			throw new RuntimeException("Error stopping Jetty instance: " + ex.toString(), ex);
		}
	}
}
